package www.openteam.com.ui.policy;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.cundong.recyclerview.EndlessRecyclerOnScrollListener;
import com.cundong.recyclerview.HeaderAndFooterRecyclerViewAdapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import www.openteam.com.R;
import www.openteam.com.adapter.policy.PrOrderAdapter;
import www.openteam.com.adapter.policy.other.PODetailedAdapter;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.ApprovalStatu;
import www.openteam.com.bean.ProOrder;
import www.openteam.com.contract.policy.PurchaseOrderApprovalContract;
import www.openteam.com.presenter.policy.PurchaseOrderApprovalPresenter;
import www.openteam.com.tool.RecyclerViewStateUtils;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.DetailedActivity;
import www.openteam.com.widget.LoadingFooter;

/**
 * Created by hyd on 2016/10/15.
 * 采购订单审批
 */

public class PurchaseOrderApprovalFragment
        extends mBaseFragment<PurchaseOrderApprovalPresenter>
        implements PurchaseOrderApprovalContract.PurchaseOrderApprovalView {


    View view;
    private ArrayList<ProOrder.DataEntity> purchaseOrderApprovals;
    private ArrayList<ProOrder.DataEntity> approvals;
    private static int pageSize = 0;
    private final String TAG = PurchaseOrderApprovalFragment.class.getSimpleName();
    int i = 0;
    private HeaderAndFooterRecyclerViewAdapter mFooterRecyclerViewAapter = null;
    private PrOrderAdapter purchaseOrderApprovalAdapter = null;
    private vHOnClickInt vHOnClickInt;
    Throwable throwable = null;
    public int changePosition = 0;
    private boolean chk ;
    @Bind(R.id.ed_1)
    EditText ed_1;
    @Bind(R.id.ed_2)
    EditText ed_2;
    @Bind(R.id.ed_3)
    EditText ed_3;
    @Bind(R.id.ed_4)
    EditText ed_4;
    @Bind(R.id.ed_5)
    Spinner ed_5;
    @Bind(R.id.query_btn)
    Button query_btn;
    @Bind(R.id.tv_1)
    TextView tv_1;
    @Bind(R.id.tv_2)
    TextView tv_2;
    @Bind(R.id.tv_3)
    TextView tv_3;
    @Bind(R.id.tv_4)
    TextView tv_4;
    @Bind(R.id.tv_5)
    TextView tv_5;
    @Bind(R.id.btn1)
    Button btn1;
    @Bind(R.id.btn2)
    Button btn2;
    @Bind(R.id.btn3)
    Button btn3;
    @Bind(R.id.child_recycleview)
    RecyclerView childRecycleview;
    private int approval=0;
    int j = -1;
    PODetailedAdapter poDetailedAdapter;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        detailGather = ((DetailedActivity) getActivity()).getDetailGather();
        chk= mySetting.getBoolean("chk",false);
    }

    private void setPurchaseOrderApprovalAdapter() {
        if (purchaseOrderApprovalAdapter == null) {
            purchaseOrderApprovalAdapter = new PrOrderAdapter(getActivity());
            purchaseOrderApprovalAdapter.addItems(purchaseOrderApprovals);
            purchaseOrderApprovalAdapter.addContext(getActivity());
            purchaseOrderApprovalAdapter.registerAdapterDataObserver(adapterDataObserver);
            purchaseOrderApprovalAdapter.buttonSetOnclick(new PrOrderAdapter.ButtonInterfacet() {
                @Override
                public void onclick(View view, int position) {
                    if (approvals.get(position).getStatusn().equals("已审核")) {
                        changePosition = position;
                        Log.d(TAG, "onclick: " + position);
                        mPresenter.unprApprovalUpdate(approvals.get(position).getId());
                    } else if (approvals.get(position).getStatusn().equals("未审核")){
                        changePosition = position;
                        Log.d(TAG, "onclick: " + position);
                        mPresenter.prApprovalUpdate(approvals.get(position).getId());
                    }else{
                        ToastUtil.showToast(getActivity(),"不可逆操作");
                    }

                }
            });
            purchaseOrderApprovalAdapter.vHSetOnclick(new PrOrderAdapter.VHInterface() {
                @Override
                public void onclick(int position) {
                    Log.d(TAG, "onclick: cs");
                    vHOnClickInt.dOnclick(approvals.get(position));
                }
            });
            mFooterRecyclerViewAapter = new HeaderAndFooterRecyclerViewAdapter(purchaseOrderApprovalAdapter);
            mRecyclerView.setAdapter(mFooterRecyclerViewAapter);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        } else {
            Log.d(TAG, "setNewAdapter: 2");
            mFooterRecyclerViewAapter.notifyDataSetChanged();
            purchaseOrderApprovalAdapter.addItems(purchaseOrderApprovals);
            if (chk) {
                purchaseOrderApprovalAdapter.buttonSetOnclick(new PrOrderAdapter.ButtonInterfacet() {

                    @Override
                    public void onclick(View view, int position) {
                        if (approvals.get(position).getStatusn().equals("已审核")) {
                            changePosition = position;
                            Log.d(TAG, "onclick: " + position);
                            mPresenter.unprApprovalUpdate(approvals.get(position).getId());
                        } else if (approvals.get(position).getStatusn().equals("未审核")) {
                            changePosition = position;
                            Log.d(TAG, "onclick: " + position);
                            mPresenter.prApprovalUpdate(approvals.get(position).getId());
                        } else {
                            ToastUtil.showToast(getActivity(), "不可逆操作");
                        }
                    }
                });
            }else {
                ToastUtil.showToast(getActivity(),"暂时没有取得权限");
            }

            purchaseOrderApprovalAdapter.vHSetOnclick(new PrOrderAdapter.VHInterface() {
                @Override
                public void onclick(int position) {
                    Log.d(TAG, "onclick: cs");
                    vHOnClickInt.dOnclick(approvals.get(position));
                }
            });
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        }
    }

    @Override
    public void onRefresh() {
        if ((mRecyclerView.getChildCount() > 0) && (!getRdsno().isEmpty() || !getOrderStatus().isEmpty() || getStartTime() != 0 || getEndTime() != 0)) {
            Log.d(TAG, "onRefresh: " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            purchaseOrderApprovals.clear();
            purchaseOrderApprovalAdapter = null;
            approvals.clear();
            mFooterRecyclerViewAapter = null;
            mPresenter.queryPrOrder(getRdsno(),getCode(),  getOrderStatus(), getStartTime(),
                    getEndTime(),getStype(),getMoreCom(), 0);
            throwable = null;
            i = 0;
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() <= 0) && (!getRdsno().isEmpty() || !getOrderStatus().isEmpty() || getStartTime() != 0 || getEndTime() != 0)) {
            Log.d(TAG, "onRefresh: else if " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            purchaseOrderApprovalAdapter = null;
            purchaseOrderApprovals.clear();
            approvals.clear();
            mPresenter.queryPrOrder(getRdsno(), getCode(),  getOrderStatus(),getStartTime(),
                    getEndTime(),getStype(),getMoreCom(), 0);
            mSwipeRefresh.setRefreshing(false);
        }
    }


    public EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
            if (state == LoadingFooter.State.Loading) {
                Log.d("@Cundong", "the state is Loading, just wait..");
                i++;
            }
            i++;
            if (throwable == null && (purchaseOrderApprovals.size() % 10 == 0)) {

                Log.d(TAG, "onLoadNextPage: jx");

                purchaseOrderApprovals = new ArrayList<ProOrder.DataEntity>();
                mPresenter.queryPrOrder(getRdsno(),  getCode(),getOrderStatus(), getStartTime(),
                        getEndTime(),getStype(),getMoreCom(), i);

                RecyclerViewStateUtils.
                        setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            } else if (throwable == null && (purchaseOrderApprovals.size() % 10 != 0)) {
                //the end
                mPresenter.queryPrOrder(getRdsno(), getCode(),  getOrderStatus(),getStartTime(),
                        getEndTime(),getStype(),getMoreCom(), i);
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            } else if (throwable != null) {
                //the end
                i = 0;
                Log.d(TAG, "onLoadNextPage:  bunull ");
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            }

        }
    };


    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            mPresenter.queryPrOrder(getRdsno(),  getCode(), getOrderStatus(),getStartTime(),
                    getEndTime(),getStype(),getMoreCom(),i);
        }
    };

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_1.setText(detail[0]);
        tv_2.setText(detail[1]);
        tv_3.setText(detail[2]);
        tv_4.setText(detail[3]);
        tv_5.setText(detail[4]);
        initSRView(view);
        mRecyclerView.addOnScrollListener(mOnScrollListener);

    }


    public void initSRView(View view ) {


        mSwipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mSwipeRefresh.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent);
        mSwipeRefresh.setOnRefreshListener(this);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getActivity());
        linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        childRecycleview.setLayoutManager(linearLayoutManager1);
        poDetailedAdapter = new PODetailedAdapter(getContext());

    }





    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initView() {
        final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        int current_day = c.get(Calendar.DAY_OF_MONTH);
        int current_month = c.get(Calendar.MONTH);
        int current_year = c.get(Calendar.YEAR);
        c.set(current_year, current_month, current_day);
        ed_3.setText(df.format(c.getTime()));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一周内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
                c.add(Calendar.DATE, -7);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一月内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH) - 1;
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一年内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR) - 1;
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        query_btn.setOnClickListener(new View.OnClickListener() {  //查询按钮
            @Override
            public void onClick(View v) {
                createProgressDialog("正在查询,请稍候....");
                if (purchaseOrderApprovalAdapter == null) {
                    purchaseOrderApprovals = new ArrayList<ProOrder.DataEntity>();
                    approvals = new ArrayList<ProOrder.DataEntity>();
                    mPresenter.queryPrOrder(getRdsno(),  getCode(), getOrderStatus(),getStartTime(),
                            getEndTime(),getStype(),getMoreCom(), pageSize);
                } else {
                    purchaseOrderApprovalAdapter.deleteItems(purchaseOrderApprovals);
                    mRecyclerView.removeAllViews();
                    approvals.clear();
                    throwable = null;
                    i = 0;
                    purchaseOrderApprovals.clear();
                    onRefresh();
                }
            }
        });
        ed_5.setSelection(0);
    }

    @Override
    protected void otherViewClick(View view) {
        ed_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectCalendar();
            }
        });
        ed_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectEndCalendar();
            }
        });
    }

    @Override
    protected PurchaseOrderApprovalPresenter loadPresenter() {
        return new PurchaseOrderApprovalPresenter();
    }

    @Override
    public String getRdsno() {
        return ed_2.getText().toString();
    }

    @Override
    public String getCode() {
        return ed_1.getText().toString();
    }

    @Override
    public String getOrderStatus() {
        return ed_5.getSelectedItemPosition()+"";
    }

    @Override
    public long getStartTime() {
        if (!ed_4.getText().toString().isEmpty()) {
            startMilli = changeMilli(ed_4.getText().toString());
        }
        return startMilli;
    }

    @Override
    public long getEndTime() {
        if (!ed_3.getText().toString().isEmpty()) {
            endMilli = changeMilli(ed_3.getText().toString());
        }
        return endMilli;
    }

    @Override
    public String getStype() {
        String stype  =  mySetting.getString("rCode","");
        Log.d(TAG, "getStype: "+stype);
        return stype;
    }

    @Override
    public String getMoreCom() {
        String moreCom =  mySetting.getString("rMoreCom","");
//        Log.d(TAG, "getMoreCom: "+moreCom);
        return moreCom;
    }


    @Override
    public void queryPOASuccess(List<ProOrder.DataEntity> data) {
        mProgressDialog.dismiss();
        j++;
        for (ProOrder.DataEntity dev : data) {
            purchaseOrderApprovals.add(dev);
            approvals.add(dev);
        }
        setPurchaseOrderApprovalAdapter();
        childRecycleview.setVisibility(View.VISIBLE);
        if (j==0){
            poDetailedAdapter.addItems(data.get(0));
            childRecycleview.setAdapter(poDetailedAdapter);
        }
        purchaseOrderApprovalAdapter.setOnLineClickListener(new PrOrderAdapter.OnLineClickListener() {
            @Override
            public void onClick(ProOrder.DataEntity item) {
                poDetailedAdapter.addItems(item);
                childRecycleview.setAdapter(poDetailedAdapter);
            }
        });
//        if (arrow_statue) {
//            touchEvent();
//        }
}

    @Override
    public void queryPOAFail(String failMsg) {
        mProgressDialog.dismiss();
        this.throwable = new Throwable();
        if (failMsg.toString().equals("暂无合适的数据")
                ) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
            ToastUtil.showToast(getActivity(), "暂无匹配数据");
        } else {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
            ToastUtil.showToast(getActivity(), "网络连接有误");
        }
    }

    @Override
    public void approvalPOASuccess(ApprovalStatu aprovalStatu) {
        mProgressDialog.dismiss();
        approval= 0;
        purchaseOrderApprovalAdapter.notifyItemChanged(changePosition,new Object());
    }

    @Override
    public void approvalPOAFail(String failMsg) {
        mProgressDialog.dismiss();
        ToastUtil.showToast(getContext(), "审核失败");
    }

    RecyclerView.AdapterDataObserver adapterDataObserver =new RecyclerView.AdapterDataObserver(){
        public void onItemRangeChanged(int positionStart, int itemCount) {
            if (approval==0) {
                purchaseOrderApprovalAdapter.changeData(changePosition, "已审核");
            }else{
                purchaseOrderApprovalAdapter.changeData(changePosition,"未审核");
            }
        }
    };

    @Override
    public void unApprovalPOASuccess(ApprovalStatu aprovalStatu) {
        mProgressDialog.dismiss();
        approval= 1;
        purchaseOrderApprovalAdapter.notifyItemChanged(changePosition);
        ToastUtil.showToast(getContext(), "取消审核成功");
    }

    @Override
    public void unApprovalPOAFail(String failMsg) {
        ToastUtil.showToast(getContext(), "取消审核失败");
    }


    public void vhOnClickInt(vHOnClickInt vHOnClickInt){
        this.vHOnClickInt= vHOnClickInt;
    }


    public interface vHOnClickInt{
        void dOnclick(ProOrder.DataEntity proOrder);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
